<template>
	<div class="content">
		<div class="top-section">
			<div class="block">
				<!-- <div style="position: relative; display: inline-block;margin-left: 10%;">
					<img src="@/assets/images/circle.png" alt="image" style="width: 65px; height: 65px; margin-left: 10px;">
					<img src="@/assets/images/circle1.png" alt="image" style="position: absolute; top: 50%; left: 50%;
										transform: translate(-30%, -60%);
								width: 20x; height: 20px;">
				</div> -->
				<div class="blockView">
					<el-icon size="30px" color="#5481F6">
						<Tickets />
					</el-icon>
				</div>
				<div class="blockLoop">
					<span class="blockValue"> {{ countList.total }} </span>
					<span class="blockText">计划总数</span>
				</div>
			</div>
			<div class="block">
				<div class="blockView">
					<el-icon size="30px" color="#5481F6">
						<DocumentChecked />
					</el-icon>
				</div>
				<div class="blockLoop">
					<span class="blockValue"> {{ countList.completedCount }} </span>
					<span class="blockText">已完成</span>
				</div>
			</div>
			<div class="block">
				<div class="blockView">
					<el-icon size="30px" color="#5481F6">
						<DocumentDelete />
					</el-icon>
				</div>
				<div class="blockLoop">
					<span class="blockValue"> {{ countList.unCompletedCount }} </span>
					<span class="blockText">未完成</span>
				</div>
			</div>
			<div class="block">
				<div class="blockView">
					<el-progress type="circle" :percentage="percentageCompleted" width="80" show-text="false" />
				</div>
				<div class="blockLoop">
					<span class="blockValue"> {{ percentageCompleted }} % </span>
					<span class="blockText">占比</span>
				</div>
			</div>
		</div>
		<div class="pageTableView">


			<div class="pageTableMenuView">
				<div class="pageTableTitle"> 计划信息</div>
				<div class="pageTableButView">
					<el-button type="primary" @click="handleIssueBatch" :disabled="multipleSelection.length == 0"
										 style="margin-right: 10px">批量下发
					</el-button>
					<!--          @click="handleAdd"-->
					<router-link to="/production/productionAdd">

						<el-button :icon="Plus">新建</el-button>
					</router-link>
				</div>
			</div>
			<div class="pageSearchView" style="padding-top: 0px;">
				<el-form :inline="true" :model="searchParam" class="demo-form-inline">
					<el-form-item label="计划号">
						<el-input v-model="searchParam.planNo"   @keyup.enter="getList" placeholder="请输入计划号" clearable style="width: 200px" />
					</el-form-item>
					<el-form-item label="产品名称">
						<el-input v-model="searchParam.productName" placeholder="请输入产品名称" clearable @keyup.enter="getList"
                      style="width: 200px" />
					</el-form-item>
					<el-form-item label="属性">
						<el-select v-model="searchParam.property" placeholder="请选择属性" style="width: 200px" clearable>
							<el-option :key="0" label="正常" :value="0" />
							<el-option :key="1" label="返工" :value="1" />
						</el-select>
					</el-form-item>

					<el-form-item>
						<el-button type="primary" :icon="Search" @click="getList()">查询</el-button>
						<el-button :icon="Refresh" @click="resetSearch()">重置</el-button>
					</el-form-item>
				</el-form>
			</div>

			<!-- 表格 -->
			<el-table class="pageTableClass" :data="paginatedData" ref="myTable" height="calc(100vh - 400px)"
								@selection-change="handleSelectionChange"
								row-key="id">
				<el-table-column type="selection" width="55" align="center" />
				<el-table-column type="expand">
					<template #default="props">
						<div m="4">
							<el-table ref="tableCil" border size="small" :data="props.row.children"
												header-cell-class-name="blueTableHeader" style="width: 85vw;margin-left: 20px">

								<el-table-column type="index" width="50" label="序号" align="center" />
								<el-table-column label="产品名称" prop="productId" align="center" show-overflow-tooltip
																 width="450">
									<template #default="scope">
										<span>{{
												productData.find((i) => i.id === scope.row.productId)?.productName
											}}</span>
									</template>
								</el-table-column>
								<el-table-column label="工艺路线名称" prop="processRouteId" align="center" width="450"
																 show-overflow-tooltip>
									<template #default="scope">
										<span>{{
												allRouteData.find((i) => i.id ===
													scope.row.processRouteId)?.processName
											}}</span>
									</template>
								</el-table-column>
								<el-table-column label="属性" prop="property" align="center" show-overflow-tooltip>
									<template #default="scope">
										<span v-if="scope.row.property == 1">返工</span>
										<span v-else>正常</span>
									</template>
								</el-table-column>
								<el-table-column label="数量" prop="planCount" align="center" show-overflow-tooltip />
								<!--                <el-table-column label="" prop="ops" width="200" align="center">-->
								<!--                  <template #default="scope">-->
								<!--                    <el-button type="text" size="small" :icon="Download"-->
								<!--                               :disabled="scope.row.status != 0" flex="right"-->
								<!--                               @click="handleIssue(scope.row, props.row)">下发-->
								<!--                    </el-button>-->
								<!--                  </template>-->
								<!--                </el-table-column>-->
							</el-table>
						</div>
					</template>
				</el-table-column>
				<el-table-column label="序号" align="center" width="70">
					<template #default="scope"> {{ (current - 1) * pageSize + scope.$index + 1 }}</template>
				</el-table-column>
				<el-table-column prop="planNo" label="计划号" min-width="150" />
				<el-table-column label="产品名称" prop="productId" show-overflow-tooltip min-width="200">
					<template #default="scope">
						<span>{{
								productData.find((i) => i.id === scope.row.children[0].productId)?.productName
							}}</span>
					</template>
				</el-table-column>
				<el-table-column label="工艺路线名称" prop="processRouteId" min-width="200" show-overflow-tooltip>
					<template #default="scope">
						<span>{{
								allRouteData.find((i) => i.id ===
									scope.row.children[0].processRouteId)?.processName
							}}</span>
					</template>
				</el-table-column>
				<el-table-column label="属性" prop="property" show-overflow-tooltip>
					<template #default="scope">
						<span v-if="scope.row.children[0].property == 1">返工</span>
						<span v-else>正常</span>
					</template>
				</el-table-column>
				<el-table-column label="数量" prop="children[0].planCount" show-overflow-tooltip />
				<el-table-column prop="planBeginTime" label="计划开始时间" min-width="200" />
				<el-table-column prop="planEndTime" label="计划结束时间" min-width="200" />
				<el-table-column prop="organizationId" label="工厂/车间" min-width="150">
					<template #default="scope">
						<span>{{ lineListAll.find((i) => i.id === scope.row.organizationId)?.orgName }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="status" label="计划状态" width="100">
					<template #default="scope">
						<div v-if="scope.row.status == 2">已完成</div>
						<div v-else> {{ scope.row.status === 0 ? '新建' : '执行中' }}</div>
					</template>
				</el-table-column>
				<el-table-column prop="type" label="计划类型" width="100">
					<template #default="scope"> {{ getTypeName(scope.row.type) }}</template>
				</el-table-column>
				<el-table-column prop="actualBeginTime" label="实际开始时间" width="180" />
				<el-table-column prop="actualEndTime" label="实际结束时间" width="180" />
				<el-table-column prop="nickname" label="创建人" width="120" />
				<el-table-column prop="createTime" label="创建时间" width="180" />
				<el-table-column label="操作" width="250" fixed="right" align="center">
					<template #default="scope">

						<!--																		<el-button type="text" size="small" @click="handleEdit(scope.row)" :icon="Edit"-->
						<!--																							 :disabled="scope.row.status === 1">编辑-->
						<!--																		</el-button>-->
						<!--																		<el-button type="danger" plain text size="small" @click="handleDel(scope.row)"-->
						<!--																							 :disabled="scope.row.status === 1" :icon="Delete">删除-->
						<!--																		</el-button>-->
						<!--																		<el-button type="danger" plain text size="small" @click="handleOver(scope.row)"-->
						<!--																							 :icon="SwitchButton">完结-->
						<!--																		</el-button>-->
						<el-button type="text" size="small" :icon="Download" :disabled="scope.row.status === 1"
											 @click="handleIssue(scope.row, scope.row.children[0])">下发
						</el-button>
						<el-dropdown placement="bottom">
							<el-button type="text" size="small" :icon="Switch">操作</el-button>
							<template #dropdown>
								<el-dropdown-menu>
									<el-dropdown-item key="1" :icon="Edit"
																		@click="handleEdit(scope.row)">
										编辑
									</el-dropdown-item>
									<el-dropdown-item key="2" :icon="Delete" :disabled="scope.row.status !== 0" style="color: #F56C6C"
																		@click="handleDel(scope.row)">
										删除
									</el-dropdown-item>
									<el-dropdown-item key="3" :icon="SwitchButton" style="color: #F56C6C"
																		@click="handleOver(scope.row)">
										完结
									</el-dropdown-item>
								</el-dropdown-menu>
							</template>
						</el-dropdown>
						<el-button text size="small" @click="showDialog(scope.row)" :icon="Tickets">详情</el-button>


					</template>
				</el-table-column>
			</el-table>
			<div class="pagePagination">
				<el-pagination background layout="total,prev, pager, next" :total="pageTotal" :page-size="pageSize"
											 :current-page="current" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
			</div>
		</div>
		<!-- 编辑/新建弹框 -->
		<el-dialog v-model="showCrud" title="计划信息" width="1000px">
			<el-form ref="ruleFormRef" :rules="rules" :model="formData" label-width="100px">
				<el-row :gutter="16">
					<el-col :span="12">
						<el-form-item label="计划时间" required prop="planBeginTime">
							<el-date-picker v-model="formData.planBeginTime" type="datetimerange"
															valueFormat="YYYY-MM-DD HH:mm:ss" range-separator="至" start-placeholder="计划开始时间"
															end-placeholder="计划结束时间" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="工厂/车间" required prop="organizationId">
							<el-tree-select v-model="formData.organizationId" check-strictly filterable
															:render-after-expand="false" :data="lineGroup" clearable />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="计划类型" required prop="type">
							<el-select v-model="formData.type" placeholder="请输入计划类型">
								<el-option v-for="item in typeData" :key="item.value" :value="item.value"
													 :label="item.label" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="良率计算" required prop="yield">
							<el-select v-model="formData.yield" placeholder="请选择属性" @change="changeCount">
								<el-option key="1" label="是" :value="true" />
								<el-option key="0" label="否" :value="false" />
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
				<template v-for="(item, index) in formData.keys" :key="index">
					<el-row :gutter="16">
						<el-col :span="12">
							<el-form-item label="产品名称" required>
								<el-select v-model="item.productId" placeholder="请选择产品名称" @change="changeProduct"
													 filterable>
									<el-option v-for="i in productData" :key="i.id" :value="i.id"
														 :label="i.productName" />
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="属性" required>
								<el-select v-model="item.property" placeholder="请选择属性" @change="changeProduct">
									<el-option key="0" label="正常" :value="0" />
									<el-option key="1" label="返工" :value="1" />
								</el-select>
							</el-form-item>
						</el-col>

						<el-col :span="12">
							<el-form-item label="路线名称" required>
								<el-select v-model="item.processRouteId" placeholder="请选择路线名称" filterable
													 @change="changeCount">
									<el-option v-for="i in item.allRouteData" :key="i.id" :value="i.id"
														 :label="i.processName" />
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="下发数量" required>
								<el-input v-model="item.planCount" placeholder="请输入下发数量" style="width: 100%"
													@input="changeCount" />
							</el-form-item>
						</el-col>
						<el-col :span="12" v-if="item.gap">
							<el-form-item :label="`原材料缺口`"> {{ item.gap || '--' }}</el-form-item>
						</el-col>
					</el-row>
				</template>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="showCrud = false">取消</el-button>
					<el-button type="primary" @click="handleSave(ruleFormRef)"
										 :disabled="formData.status === 1">保存</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>
<script lang="ts" setup>
import { ref, computed, watch, onMounted, nextTick } from 'vue';
import axiosInstance from '@/utils/http/api';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useBaseDataPlanData } from '@/hooks/production/productionPlan';
import SearchForm from '@/components/SearchForm.vue';
import {
	ProductionPlanDetailApi,
	productBaseDataPlanApiQuery,
	queryByPlanIdDetail, issuePlan
} from '@/api/production/productionPlan';
import {
	CircleClose,
	CirclePlus,
	Delete,
	Edit,
	Download,
	Tickets,
	Plus,
	SwitchButton,
	Switch,
	Search,
	Refresh
} from '@element-plus/icons-vue';
import * as echarts from 'echarts';
import type { ComponentSize, FormInstance, FormRules } from 'element-plus';

const {
	searchParam,
	pageSize,
	current,
	pageTotal,
	paginatedData,
	searchFields,
	productData,
	allRouteData,
	materialData,
	lineListAll,
	typeData,
	lineGroup,
	handleAddSubmit,
	handleSearch,
	handleSizeChange,
	handleCurrentChange,
	addBaseDataPlan,
	deleteBaseDataPlan,
	handleIssue,
	isLoading
} = useBaseDataPlanData();
const index = ref(0);
const expandedRows = ref([]);
const chartDom = ref({});
const dialogRef = ref(false);
const echartsContainer = ref(null);

interface RuleForm {
}

const handleIssueBatch = () => {
	if (multipleSelection.value.find(item => item.status === 1)) {
		ElMessage.error('存在不可下发数据');
		return false;
	}

	ElMessageBox.confirm('是否确认下发？', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'success'
	})
		.then(async () => {
			const param = [];
			for (const item of multipleSelection.value) {
				if (item.children) {
					param.push(item.children[0]);
				}
			}
			await issuePlan(param).then(async (res) => {
				if (res.code !== 200) {
					ElMessage.error(res.message);
					return;
				}

				ElMessage.success('下发成功');
				getList();
			});
		})
		.catch(() => {
		});


	console.log(param);
};

const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules<RuleForm>>({
	planBeginTime: [
		{ required: true, message: '请选择计划时间', trigger: 'blur' }
	],
	organizationId: [
		{ required: true, message: '请选择工厂/车间', trigger: 'blur' }
	],
	type: [
		{ required: true, message: '请选择计划类型', trigger: 'blur' }
	],
	yield: [
		{ required: true, message: '请选择是否良率计算', trigger: 'blur' }
	]
});
const formData = ref({
	planNo: '',
	name: '',
	planBeginTime: null,
	planEndTime: null,
	actualBeginTime: null,
	actualEndTime: null,
	organizationId: '',
	status: '0',
	yield: false,
	type: '0',
	keys: [
		{
			productId: '',
			allRouteData: '',
			materialBom: '',
			index: index.value,
			status: 1
		}
	]
});


const onCloseButton = () => {
	dialogRef.value = false;
};
// 重置搜索条件
const resetSearch = () => {
	searchParam.value = {};

	// current.value = 1
	getList();
};

import { useRoute, useRouter } from 'vue-router';

const router = useRouter();
const showDialog = (row) => {
	router.push('/production/productionDetail?planNo=' + row.planNo + '&planNoId=' + row.id);

};
const changeProduct = () => {
	// keysArray(e, index);
	const keys = formData.value.keys[0];
	keys.gap = null;
	if (keys.productId !== undefined && keys.productId !== null
		&& keys.property !== undefined && keys.property !== null && keys.productId !== '') {
		keys.processRouteId = null;
		keys.allRouteData = [];
		axiosInstance.post('/api/basedataProcessRoute/listProcesssRoute', {
			productId: keys.productId,
			property: keys.property,
			current: 0,
			pageSize: 999999,
			processPublished: 1
		}).then(res => {
			const filteredAllRouteData = res.data.records;
			formData.value.keys[0] = {
				...keys,
				allRouteData: filteredAllRouteData
			};
		});
	}
};


// 输入下发数量计算原材料缺口
const changeCount = () => {
	const keys = formData.value.keys[0];
	if (keys.processRouteId && keys.planCount && formData.value.yield !== null) {
		// const gap = keys.gapParam.count - (keys.planCount * keys.gapParam.numPutCompare);
		axiosInstance.get('/api/planOrder/queryStorageByRouteId', {
			params: {
				yield: formData.value.yield,
				processRouteId: keys.processRouteId,
				orderCount: keys.planCount
			}
		}).then(res => {
			formData.value.keys[0].gap = res.data.count;
		});
		// formData.value.keys[0].gap = gap.toFixed(3);
	}
};
const keysArray = (e: string, index: number) => {
	const filteredAllRouteData = allRouteData.value.filter((i) => i.productId === e);

	const filteredMaterialBom = materialData.value.filter((i) => i.productId === e);

	formData.value.keys[index] = {
		...formData.value.keys[index],
		productId: e,
		allRouteData: filteredAllRouteData,
		materialBom: filteredMaterialBom
	};
};
const getTypeName = (type: string) => {
	const name = typeData.value.find((item: any) => item.value === type);
	return name ? name.label : '';
};

const typeList = ref([
	{ label: '未完成', value: '0' },
	{ label: '已完成', value: '1' }
]);

const isEdit = ref(false); // 是否编辑
const showCrud = ref(false); // 编辑/新建弹框

// 新建记录
const handleAdd = () => {
	isEdit.value = false;
	formData.value = {
		planNo: '',
		name: '',
		keys: [
			{
				productId: '',
				allRouteData: '',
				index: index.value,
				status: 1
			}
		]
	};
	showCrud.value = true;
};

const addFormData = ref(null);

// 编辑记录
const handleEdit = (row: any) => {
	// isEdit.value = true;
	ProductionPlanDetailApi({ planId: row.id }).then((res) => {

		formData.value = {
			...row,
			planBeginTime: [row.planBeginTime, row.planEndTime],
			keys: res.data.records
		};
		// changeCount();
		localStorage.setItem('addFormData', JSON.stringify(formData.value));
		router.push('/production/productionAdd?id=' + row.id);

		// res.data.records.map((item: any, index: number) => {
		//   return keysArray(item.productId, index);
		// });
	});

	// showCrud.value = true;
};


const handleOver = (row: any) => {
	ElMessageBox.confirm('确定完结该条记录吗？', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	}).then(async () => {
		axiosInstance.post('/api/planOrder/updateByIdStatus', { id: row.id, status: '1' })
			.then(res => {
				if (res.code === 200) {
					ElMessage.success('操作成功');
					getList();
				} else {
					ElMessage.error(res.message);
				}
			});
	}).catch(() => {
	});
};
// 删除记录
const handleDel = (row: any) => {
	ElMessageBox.confirm('确定删除该条记录吗？', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	}).then(async () => {
		await deleteBaseDataPlan(row.id);
	}).catch(() => {
	});
};

// 保存记录 计划信息保存
const handleSave = async (formEl: FormInstance | undefined) => {
	await formEl.validate((valid, fields) => {
		if (valid) {
			handleAddSubmit(formData.value, (() => {
				showCrud.value = false;
			}));
		}
	});
};


const multipleSelection = ref([]);

const handleSelectionChange = (val) => {
	multipleSelection.value = val;
};

// 展开行处理
const expandedRowKeys = ref<string[]>([]);
const handleExpandChange = (row, expanded) => {
	if (expanded) {
		rowChildren(row);
		expandedRows.value.push(row.id);
	} else {
		const index = expandedRows.value.indexOf(row.id);
		if (index > -1) {
			expandedRows.value.splice(index, 1);
		}
	}

	// else {
	//   getList();
	// }
};

function collapseAll() {
	expandedRows.value = [];
}

const rowChildren = (row: any) => {
	ProductionPlanDetailApi({ planId: row.id }).then((res) => {
		if (res.code !== 200) {
			ElMessage.warning(res.message);
			return false;
		}
		const listGroup = paginatedData.value.map((item) => {
			if (item.id === row.id) {
				return { ...item, children: res.data.records };
			}
			return item;
		});
		paginatedData.value = listGroup;
	});
};

const myTable = ref(null);
// 获取列表
const getList = async () => {
	try {
		const response = await productBaseDataPlanApiQuery({
			...searchParam.value,
			current: current.value,
			pageSize: pageSize.value
		});
		if (response.code === 200) {
			paginatedData.value = response.data.records;
			pageTotal.value = response.data.total;
			collapseAll();
		} else {
			ElMessage.warning(response.message);

		}
	} catch (error) {
		ElMessage.error('获取列表失败');
	}
	isLoading.value = false;
};


const percentageCompleted = computed(() => {
	const { completedCount, total } = countList.value;
	// 确保总数不为0以避免除以0的错误，并保留一位小数
	return total ? Number(((completedCount / total) * 100).toFixed(1)) : 0;
});


const countList = ref({});

onMounted(() => {
	getList();
	axiosInstance.post('/api/planOrder/count', {})
		.then(res => {
			countList.value = res.data;
		});
});
</script>
<style scoped>
.top-section {
	display: flex;
	justify-content: space-between;
	font-size: 16px;
	height: 100px;
}

.block {
	background-color: #fff;
	width: 25%;
	margin-right: 10px;
	border-radius: 10px;
	display: flex;
	align-items: center;
	justify-content: center;
}

.block:last-child {
	margin-right: 0;
}

.block-inner {
	display: flex;
	align-items: center;
}

.text {
	font-size: 14px;
	color: #333;
}

.blockView {
	height: 70px;
	width: 70px;
	background-color: #E4EAF7;
	display: flex;
	align-items: center;
	justify-content: center;
	border-radius: 50%;
}

.blockLoop {
	height: 87px;
	padding-left: 50px;
	display: flex;
	flex-direction: column;
	justify-content: center;
}

.blockValue {
	color: #5481F6;
	padding-bottom: 5px;
	font-size: 18px;
}

.blockText {
	color: black;
	font-weight: 700;
}

</style>
